﻿using UnityEngine;
using System.Collections;

/// <summary>
/// 粒子裁剪脚本 use UIPanel
/// 
/// binding this script to particle system
/// reference a uiwidget which is it's parent
/// then clip particle system in the arena
///  ---
/// |   |
///  ___
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(ParticleSystemRenderer))]
public class UIParticle : MonoBehaviour
{    
    private UIPanel panel;
    private ParticleSystemRenderer pRenderer;
    private Material dyMaterial;
    private UIWidget cover;

	// Use this for initialization
	void Start ()
	{
        panel = GetComponentInParent<UIPanel>();
	    pRenderer = GetComponent<ParticleSystemRenderer>();

	    dyMaterial = new Material(Shader.Find("Hidden/Unlit/Transparent Colored 1"))
	    {
	        renderQueue = 4000,
	        mainTexture = pRenderer.sharedMaterial.mainTexture
	    };

	    pRenderer.material = dyMaterial;
	}

    // OnWillRenderObject is called once per frame before rendering
    void OnWillRenderObject()
    {
        if (panel != null && panel.hasClipping)
        {
            if (cover != null && cover.isActiveAndEnabled && cover.drawCall != null)
            {
                dyMaterial.renderQueue = cover.drawCall.renderQueue;
            }

            Vector4 cr = panel.drawCallClipRange;
            Vector2 soft = panel.clipSoftness;

            Vector2 sharpness = new Vector2(1000.0f, 1000.0f);
            if (soft.x > 0f) sharpness.x = cr.z / soft.x;
            if (soft.y > 0f) sharpness.y = cr.w / soft.y;

            float scale = 1.0f / transform.lossyScale.x;
            Vector3 position = -panel.transform.position * scale;

            Vector4 clipRange = new Vector4(
                    -cr.x / cr.z,
                //+position.x / cr.z,
                    -cr.y / cr.w,
                //+position.y / cr.w,
                    1f / cr.z * scale,
                    1f / cr.w * scale);
            
            //UnityEngine.Debug.Log(" clipRange  " + clipRange.ToString());

            dyMaterial.SetVector(Shader.PropertyToID("_ClipRange0"), clipRange);
            dyMaterial.SetVector(Shader.PropertyToID("_ClipArgs0"), new Vector4(sharpness.x, sharpness.y, 0, 1));
        }
	}

    // Destroy the dyMaterial to avoid leaking
    void OnDestroy()
    {
        DestroyImmediate(dyMaterial);
        dyMaterial = null;
    }
}
